const router = require('koa-router')()
const db = require('../db')

router.post('/add', async ctx => { 
    // ctx.redirect('/')  手动路由的重定向  
    let obj = ctx.request.body
    obj.othters = {weight:obj.othters}
    console.log(obj)
    let list = {
        succeed: '插入成功',
        error:'插入失败'
    }
    let res = await db.isconnection().insert('user', obj)
    if (res.n === 1) { 
        await ctx.render('response', {
            msg:list.succeed
        })
        return
    }
    await ctx.render('response', {
        msg:list.error
    })
})

router.post('/edit', async ctx => { 
    let id = db.isconnection().getObjectId(ctx.request.body.id)
    let name = ctx.request.body.name
    let age = ctx.request.body.age
    let weight = ctx.request.body.othters.weight
    let list = {
        succeed: '更新成功',
        error:'更新失败'
    }
    let res = await db.isconnection().update('user', { _id: id }, { name, age, othters: { weight } })
    if(res.ok === 1){ 
        await ctx.render('response', {
            msg: list.succeed
        })
        return
    }
    await ctx.render('response', {
        msg:list.error
    })
})

module.exports = router